<template>
  <div class="container">
    <div class="content">
      <div class="prompt" style="text-align: left">
        <ul>
          <li>
            <i class="el-icon-question" style="color: #81d3f8; font-size: 20px">
            </i
            ><i>操作说明：</i>
          </li>
          <li>
            <i
              >1、新建时，每个班次的值班开始时间自动填充，其中表格首行第一个班次的值班开始时间固定为排班开始时间。</i
            >
          </li>
          <li>
            <i>2、复制时，系统自动将复制勾选的行并追加粘贴到表格的最后。</i>
          </li>
          <li>
            <i
              >3、导入时，Excel中sheet的名称应和排班方案的名称保持一致，导入的数据会拼接在已有数据的后面。</i
            >
          </li>
          <li><i>4、启用状态下也可以修改排班明细 </i></li>
        </ul>
      </div>
      <div class="btnArr">
        <template v-for="(i, index) in btnConfig">
          <el-button
            size="mini"
            class="btn-text-blue"
            :key="index"
            :type="i.type"
            :icon="i.icon"
            @click="i.methods"
            >{{ i.text }}</el-button
          >
        </template>
      </div>
      <div class="table">
        <el-table
          class="sonTable"
          :header-cell-style="{ color: '#000' }"
          border
          stripe
          :data="sonTableData"
          size="mini"
          ref="editTable"
        >
          <el-table-column
            type="selection"
            fixed="left"
            width="40"
            align="center"
          ></el-table-column>
          <el-table-column
            type="index"
            width="40"
            align="center"
            label="序号"
          ></el-table-column>
          <template v-for="(item, index) in customData">
            <el-table-column
              :label="item.label"
              :align="item.textAlign ? item.textAlign : 'center'"
              :width="item.width"
              :min-width="item.minWidth"
              :prop="item.prop"
              :key="index"
            >
              <template v-if="item.subColumn">
                <template v-for="(subItem, subIndex) in item.subColumn">
                  <el-table-column
                    :label="subItem.label"
                    :align="subItem.textAlign ? subItem.textAlign : 'center'"
                    :width="subItem.width"
                    :min-width="item.minWidth"
                    :prop="subItem.prop"
                    :key="subIndex"
                  >
                    <template slot="header">
                      <span class="star" v-if="subItem.blanked == 0">*</span>
                      <span class="starName">{{ subItem.label }}</span>
                    </template>
                    <template slot-scope="scope">
                      <template
                        v-if="
                          subItem.type == 'date' &&
                            scope.$index != 0 &&
                            subItem.isEdit &&
                            scope.row[`status${subItem.index}`] == 0
                        "
                      >
                        <el-date-picker
                          v-model="scope.row[subItem.prop]"
                          :title="scope.row[subItem.prop]"
                          class="w100"
                          type="date"
                          size="mini"
                          @change="(val) => inputChange(val, scope.row)"
                          :placeholder="subItem.placeholder || '选择日期'"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :picker-options="subItem.pickerOptions"
                          :clearable="true"
                          format="yyyy-MM-dd HH:mm"
                          value-format="yyyy-MM-dd HH:mm"
                        ></el-date-picker>
                      </template>
                      <template
                        v-else-if="
                          subItem.type == 'user' &&
                            subItem.blanked != 1 &&
                            scope.row[`status${subItem.index}`] == 0
                        "
                      >
                        <memberSelect
                          :currentRow="scope.row"
                          :currentProp="subItem.members"
                          :currentOrg="currentOrg"
                          :staff="scope.row[subItem.members]"
                          :staffType="allInfo.staffType"
                          ref="memberSelect"
                        ></memberSelect>
                      </template>
                      <template v-else>
                        <span
                          class="text"
                          v-if="subItem.scopeType == 'formate'"
                          v-html="
                            subItem.method(scope.row)
                              ? subItem.method(scope.row)
                              : '-'
                          "
                        ></span>
                        <span v-else class="text">
                          {{
                            subItem.formatter
                              ? subItem.formatter(scope.row)
                              : formatterNull(scope.row[scope.column.property])
                          }}
                        </span>
                      </template>
                    </template>
                  </el-table-column>
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column
            align="center"
            label="操作"
            prop="operate"
            width="60"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                v-if="isShow(scope.row, scope.$index)"
                @click="() => deleteOnce(scope.row, scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <dialogPublic
      :title="'导入文件'"
      :show.sync="show"
      width="40%"
      :noFootBtn="true"
    >
      <div style="text-align: left; height: 200px" v-if="show">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :on-change="handleChange"
          :multiple="false"
          :auto-upload="false"
          accept=".xls,.xlsx"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
            >上传到服务器</el-button
          >
          <div class="el-upload__tip" slot="tip">
            只能上传excle文件，且不超过500kb
          </div>
        </el-upload>
        <el-button v-if="path != ''" type="text" @click="downLoadResult"
          >下载错误备注文件</el-button
        >
      </div>
    </dialogPublic>
  </div>
</template>

<script>
import { importSchedulPlan } from "@/api/operationManagement/runningSchedule.js";
import memberSelect from "./memberSelect.vue";
export default {
  components: { memberSelect },
  props: {
    allInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    currentOrg: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      uploadUrl: `${process.env.VUE_APP_BASEURL}/eam-service-operation/schedule/import`,
      path: "",
      uploadFile: null,
      show: false,
      items: [],
      btnConfig: [
        {
          text: "新建",
          icon: "el-icon-plus",
          methods: () => {
            this.add();
          },
        },
        {
          text: "复制",
          icon: "el-icon-document-copy",
          methods: () => {
            this.copy();
          },
        },
        {
          text: "导入",
          icon: "el-icon-upload2",
          methods: () => {
            this.import();
          },
        },
        {
          text: "导出",
          icon: "el-icon-download",
          methods: () => {
            this.export();
          },
        },
        {
          text: "下载模板",
          icon: "el-icon-download",
          methods: () => {
            this.download();
          },
        },
      ],
      sonTableData: [],
      customData: [],
      currentRow: {},
      currentItem: {},
    };
  },
  watch: {
    allInfo: {
      handler(val) {
        this.sonTableData = [];
        this.customData = [];
        this.items = val.items;
        //this.sonTableData = JSON.parse(JSON.stringify(val.shiftList));
        this.init();
      },
    },
    sonTableData: {
      handler(val) {
        if (val.length > 0) {
          let endTime = val[val.length - 1][`endTime${this.items.length - 1}`];
          this.$emit("handleEndTime", endTime);
        }
      },
    },
  },
  methods: {
    //初始化排班明细
    init() {
      this.items.forEach((item, index) => {
        const obj = {
          label: `${item.name} (${item.startTime}~${item.endTime})`,
          subColumn: [
            {
              label: "值班开始时间",
              prop: `startTime${index}`,
              type: "date",
              blanked: 0,
              width: 200,
              isEdit: index == 0 ? true : false,
              index: index,
            },
            {
              label: "值班人员",
              prop: `members${index}`,
              members: `staffs${index}`,
              type: "user",
              scopeType: "formate",
              blanked: item.blanked,
              width: this.items.length > 3 ? 300 : null,
              minWidth: this.items.length <= 3 ? 300 : null,
              index: index,
              method: (row) => {
                return this.handleMemberInfo(row[`staffs${index}`]);
              },
            },
          ],
        };
        this.customData.push(obj);
      });
      this.handleTableData();
    },
    //处理人员数据
    handleMemberInfo(data) {
      let dom;
      switch (this.allInfo.staffType) {
        case "0":
          dom = `<div style="text-align: left">值班长：${data
            .filter((item) => item.type == "0")
            .map((item) => item.staffName)
            .join()}</div>
               <div style="text-align: left">值班员：${data
                 .filter((item) => item.type == "2")
                 .map((item) => item.staffName)
                 .join()}</div>`;
          break;
        case "1":
          dom = `<div style="text-align: left">值守：${data
            .filter((item) => item.type == "1")
            .map((item) => item.staffName)
            .join()}</div>`;
          break;
        case "2":
          dom = `<div style="text-align: left">值班员：${data
            .filter((item) => item.type == "2")
            .map((item) => item.staffName)
            .join()}</div>`;
          break;
        default:
          dom = `<div style="text-align: left">值班领导：${data
            .filter((item) => item.type == "3")
            .map((item) => item.staffName)
            .join()}</div>
               <div style="text-align: left">值班人员 ：${data
                 .filter((item) => item.type == "4")
                 .map((item) => item.staffName)
                 .join()}</div>`;
          break;
      }
      return dom;
    },
    //处理表格数据
    handleTableData() {
      this.allInfo.shiftList.forEach((item) => {
        let obj = {};
        item.forEach((child, i) => {
          obj[`id${i}`] = child.id;
          obj[`name${i}`] = child.name;
          obj[`startTime${i}`] = child.startTime;
          obj[`endTime${i}`] = child.endTime;
          obj[`blanked${i}`] = child.blanked;
          obj[`staffs${i}`] = child.staffs;
          obj[`status${i}`] = child.status;
          obj[`members${i}`] = this.handleMemberInfo(child.staffs);
        });
        this.sonTableData.push(obj);
      });
    },
    /**判断空值默认- */
    formatterNull(text) {
      if (text === null || text === undefined || text === "") {
        return "-";
      } else {
        return text;
      }
    },
    //时间格式
    dateFrm() {
      return "yyyy-MM-dd HH:mm";
    },
    //改变时间
    inputChange(val, row) {
      let time = `${val.split(" ")[0]} ${this.items[0].startTime}`;
      row["startTime0"] = time;
      this.items.forEach((item, index) => {
        if (index != 0) {
          row[`startTime${index}`] = row[`endTime${index - 1}`];
        }
        row[`endTime${index}`] = this.computedTime(
          row[`startTime${index}`],
          item.duration
        );
      });
    },
    isShow(row, index) {
      let result = true;
      this.items.forEach((item, index) => {
        if (row[`status${index}`] != 0) {
          result = false;
        }
      });
      return result;
    },
    //文件上传之前
    handleChange(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      this.uploadFile = formData;
    },
    submitUpload() {
      importSchedulPlan({ id: this.allInfo.id }, this.uploadFile).then(
        (res) => {
          if (typeof res.data == "string") {
            this.path = `eam-service-operation/${res.data}`;
            this.$message.error("导入失败，请下载批复文件查看");
          } else {
            this.addTableList(res.data);
            this.$message.success("导入成功");
            this.show = false;
          }
        }
      );
    },
    //点击下载批复文件
    downLoadResult() {
      this.$utils.downloadFile(null, "排班明细批复", this.path);
    },
    //添加导入的数据
    addTableList(data) {
      this.sonTableData = [];
      data.forEach((item) => {
        let obj = {};
        item.forEach((child, i) => {
          obj[`id${i}`] = child.id;
          obj[`name${i}`] = child.name;
          obj[`startTime${i}`] = child.startTime;
          obj[`endTime${i}`] = child.endTime;
          obj[`blanked${i}`] = child.blanked;
          obj[`staffs${i}`] = child.staffs;
          obj[`status${i}`] = child.status;
          obj[`members${i}`] = child.staffs
            .map((item) => {
              return item.staffName;
            })
            .join(", ");
          obj[`membersId${i}`] = child.staffs
            .map((item) => {
              return item.staffBy;
            })
            .join(", ");
        });
        this.sonTableData.push(obj);
      });
    },
    //计算结束时间
    computedTime(startTime, dutyTime) {
      let times =
        new Date(startTime).getTime() + parseFloat(dutyTime) * 60 * 60 * 1000;
      return this.$utils.TimeFormat(times, 3);
    },
    //新建
    add() {
      let obj = {};
      let len = this.sonTableData.length;
      this.items.forEach((item, index) => {
        obj[`name${index}`] = item.name;
        obj[`blanked${index}`] = item.blanked;
        if (len == 0) {
          if (index == 0) {
            obj[`startTime${index}`] = this.allInfo.startTime;
          } else {
            obj[`startTime${index}`] = obj[`endTime${index - 1}`];
          }
        } else {
          if (index == 0) {
            obj[`startTime${index}`] = this.sonTableData[len - 1][
              `endTime${this.items.length - 1}`
            ];
          } else {
            obj[`startTime${index}`] = obj[`endTime${index - 1}`];
          }
        }
        obj[`endTime${index}`] = this.computedTime(
          obj[`startTime${index}`],
          item.duration
        );
        obj[`members${index}`] = "";
        obj[`membersId${index}`] = "";
        obj[`staffs${index}`] = [];
        obj[`status${index}`] = 0;
      });
      this.sonTableData.push(obj);
    },
    //删除一行
    deleteOnce(row, index) {
      this.$confirm("确定要删除这条排班明细吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.sonTableData.splice(index, 1);
        })
        .catch((e) => {});
    },
    //复制
    copy() {
      let selectRow = this.$refs.editTable.selection;
      if (selectRow.length == 0) {
        this.$alert("请选择至少一行数据!", "", {
          confirmButtonText: "确定",
          center: true,
        });
      } else {
        selectRow.forEach((item) => {
          let copyData = JSON.parse(JSON.stringify(item));
          let len = this.sonTableData.length;
          this.items.forEach((item, index) => {
            copyData[`name${index}`] = item.name;
            copyData[`blanked${index}`] = item.blanked;
            if (index == 0) {
              copyData[`startTime${index}`] = this.sonTableData[len - 1][
                `endTime${this.items.length - 1}`
              ];
            } else {
              copyData[`startTime${index}`] = copyData[`endTime${index - 1}`];
            }
            copyData[`endTime${index}`] = this.computedTime(
              copyData[`startTime${index}`],
              item.duration
            );
            let staffs = copyData[`staffs${index}`].map((i) => {
              let obj = {
                staffName: i.staffName,
                staffBy: i.staffBy,
                type: i.type,
              };
              return obj;
            });
            copyData[`staffs${index}`] = staffs;
            copyData[`status${index}`] = 0;
            delete copyData[`id${index}`];
          });
          this.sonTableData.push(copyData);
        });
        this.$refs.editTable.clearSelection();
      }
    },
    //导入
    import() {
      this.show = true;
    },
    //导出
    export() {
      let path = "eam-service-operation/schedule/export?id=" + this.allInfo.id;
      let fileName = `${this.allInfo.name}排班明细`;
      this.$utils.downloadFile(this.allInfo.id, fileName, path);
    },
    //下载模板
    download() {
      let path =
        "eam-service-operation/schedule/template?id=" + this.allInfo.id;
      let fileName = `${this.allInfo.name}排班明细模板`;
      this.$utils.downloadFile(this.allInfo.id, fileName, path);
    },
    getTableData() {
      let tableData = [];
      let result = true;
      this.sonTableData.forEach((item, index) => {
        tableData[index] = [];
        for (let i = 0; i < this.items.length; i++) {
          let obj = {
            name: item[`name${i}`],
            startTime: item[`startTime${i}`],
            endTime: item[`endTime${i}`],
            blanked: item[`blanked${i}`],
            staffs: item[`staffs${i}`],
            status: item[`status${i}`],
          };
          if (item[`blanked${i}`] == 0 && item[`staffs${i}`].length == 0) {
            result = false;
          }
          item[`id${i}`] && (obj.id = item[`id${i}`]);
          tableData[index].push(obj);
        }
      });
      if (result) {
        return tableData;
      } else {
        return null;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  .label {
    width: 80px;
    margin: 0 20px 0 5px;
    span::before {
      content: "*";
      color: red;
      margin-right: 4px;
    }
  }
  .content {
    flex: 1;
    width: calc(100% - 85px);
    .prompt {
      margin-left: 20px; //
    }
    .btnArr {
      text-align: left;
      margin: 20px 0;
    }
    .table {
      width: 100%;
      height: calc(100% - 180px);
      overflow: auto;
    }
  }
}
.star {
  color: #f56c6c;
  font-size: 14px;
  margin-right: 4px;
}
.starName {
  font-size: 14px;
  font-weight: bold;
}
.text {
  font-size: 14px;
}
</style>
